package com.hopu.controller;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hopu.domain.Menu;
import com.hopu.domain.Role;
import com.hopu.domain.User;
import com.hopu.domain.UserRole;
import com.hopu.entity.PageEntity;
import com.hopu.entity.ResponseEntity;
import com.hopu.service.IRoleService;
import com.hopu.service.IUserRoleService;
import com.hopu.service.IUserService;
import com.hopu.utils.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IUserRoleService userRoleService;
    //跳转角色列表页面
    @RequestMapping("/tolistPage")
    public String tolistPage(){
        return "admin/role/role_list";
    }
    //查询角色列表数据
    @RequestMapping("/list")
    @ResponseBody
    public PageEntity list(int page, int limit, Role role, Model model){
        IPage<Role> page1 = roleService.page(new Page<Role>(page, limit));
        return new PageEntity(page1);
    }
    //跳转添加页面
    @RequestMapping("/toAddPage")
    public String toAddPage(){
        return "admin/role/role_add";
    }
    //跳转更新页面
    @RequestMapping("/toUpdatePage")
    public String toUpdatePage(String id ,Model model){
        Role id1 = roleService.getOne(new QueryWrapper<Role>().eq("id", id));
        model.addAttribute("role",id1);
        return "admin/role/role_update";
    }
    //角色添加
    @RequestMapping("/save")
    @ResponseBody
    public ResponseEntity saveRole(Role role){
        Role role1 = roleService.getOne(new QueryWrapper<Role>().eq("role", role.getRole()));
        if (role1!=null){
            return ResponseEntity.error("角色名已存在");
        }
        role.setId(UUIDUtils.getID());
        role.setCreateTime(new Date());
        roleService.save(role);
        return ResponseEntity.success("添加角色成功");
    }
    //角色更新
    @RequestMapping("/update")
    @ResponseBody
    public ResponseEntity updateRole(Role role){
        role.setUpdateTime(new Date());
        roleService.updateById(role);
        return ResponseEntity.success("更新角色成功");
    }
    //角色删除
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseEntity deleteRole(@RequestBody List<Role> roles ){
        List ids = new ArrayList();
        try{
            for (Role role:roles){
                if ("root".equals(role.getRole())){
                    return ResponseEntity.error("root角色不能删除");
                }
                ids.add(role.getId());
            }
            roleService.removeByIds(ids);
            return ResponseEntity.success("删除角色成功");

        }catch (Exception e){
            e.printStackTrace();
           return ResponseEntity.error("删除角色失败");
        }
    }
    //跳转角色分配权限页面
    @RequestMapping("/toSetMenuPage")
    public String toSetMenuPage(String id,Model model){
        model.addAttribute("role_id",id);
        return "admin/role/role_setMenu";
    }

    //设置权限
    @ResponseBody
    @RequestMapping("/setMenu")
    public ResponseEntity setMenu(String id, @RequestBody ArrayList<Menu> menus){

        roleService.setMenu(id,menus);
        return ResponseEntity.success("设置权限成功");
    }

    /**
     * 查询用户关联的角色列表
     */
    @ResponseBody
    @RequestMapping("/roleList")
    public PageEntity List(String userId, Role role){
        List<UserRole> userRoles = userRoleService.list(new QueryWrapper<UserRole>().eq("user_id", userId));

//        QueryWrapper<Role> queryWrapper = new QueryWrapper<Role>();
//        if (role!=null){
//            if (!StringUtils.isEmpty(role.getRole())) queryWrapper.like("role", role.getRole());
//        }
//        List<Role> roles = roleService.list(queryWrapper);
        List<Role> roles = roleService.list();

        List<JSONObject> list = new ArrayList<JSONObject>();
        // 同样需要对用户已经关联的角色进行勾选，根据layui需要填充一个LAY_CHECKED字段
        for (Role role2 : roles) {
            JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(role2));
            boolean rs = false;
            for (UserRole userRole : userRoles) {
                if (userRole.getRoleId().equals(role2.getId())) {
                    rs = true;
                }
            }
            jsonObject.put("LAY_CHECKED", rs);
            list.add(jsonObject);
        }
        return new PageEntity(list.size(), list);
    }

}
